package com.pajx.testopengles.word

import android.content.Context
import android.opengl.GLES20
import android.util.Log
import com.pajx.testopengles.util.GLHelper
import java.nio.FloatBuffer

/**
 *User: RandBII
 *Date: 2020/8/18
 *Description:
 */
class SimpleShape(context: Context, shape: Shape) : RenderAble(context) {

    private val mContext: Context = context
    private val mShape = shape

    private var mProgram = -1
    private var mPositionHandle = -1
    private var mColorHandle = -1
    private var mMVPMatrixHandle = -1

    private val COOR_STRIDE = Cons.DIMENSION_3 * 4
    private val COLOR_STRIDE = Cons.DIMENSION_4 * 4
    private var mVertexBuffer: FloatBuffer? = null
    private var mColorBuffer: FloatBuffer? = null

    private val shaderCode = GLHelper.loadShaderAsserts(context, "world_vert.glsl")
    private val fragmentCode = GLHelper.loadShaderAsserts(context, "world_frag.glsl")

    init {
        mVertexBuffer = GLHelper.getFloatBuffer(shape.mVertex)
        mColorBuffer = GLHelper.getFloatBuffer(shape.mColors)

        val shaderId = GLHelper.loadShader(GLES20.GL_VERTEX_SHADER, shaderCode)
        val fragmentId = GLHelper.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentCode)

        mProgram = GLES20.glCreateProgram()

        GLES20.glAttachShader(mProgram, shaderId)
        GLES20.glAttachShader(mProgram, fragmentId)
        GLES20.glLinkProgram(mProgram)
        Log.e("-->", "program-->${mProgram}")
        Log.e("-->", "shaderId-->${shaderId}")
        Log.e("-->", "fragmentId-->${fragmentId}")
//        Log.e("-->", "context-->${context}")
//        Log.e("-->", "shaderCode-->${shaderCode}")
//        Log.e("-->", "fragmentCode-->${fragmentCode}")

        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition")
        mColorHandle = GLES20.glGetAttribLocation(mProgram, "color")
        mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix")
        GLES20.glValidateProgram(mProgram)

    }


    override fun draw(matrix: FloatArray) {

        GLES20.glUseProgram(mProgram)
        GLES20.glEnableVertexAttribArray(mPositionHandle)
        GLES20.glEnableVertexAttribArray(mColorHandle)
        GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, matrix, 0)

        GLES20.glVertexAttribPointer(
            mPositionHandle,
            Cons.DIMENSION_3,
            GLES20.GL_FLOAT,
            false,
            COOR_STRIDE,
            mVertexBuffer
        )

        GLES20.glVertexAttribPointer(
            mColorHandle,
            Cons.DIMENSION_4,
            GLES20.GL_FLOAT,
            false,
            COLOR_STRIDE,
            mColorBuffer
        )

        GLES20.glLineWidth(4f)
        GLES20.glDrawArrays(mShape.mType, 0, mShape.mVertex.size / Cons.DIMENSION_3)

        GLES20.glDisableVertexAttribArray(mPositionHandle)
    }
}